﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using QLKDS.DAL;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using QLKDS.DTO;

namespace QLKDS.Forms
{
    public partial class frmExportBooks : XtraForm
    {
        private CustomerManager customerManager = new CustomerManager();
        private StoreManager storeManager = new StoreManager();
        private BookStoreManager bookStoreManager = new BookStoreManager();
        private BooksManager booksManager=new BooksManager();
        private IList<ExportBookDetailInfo> L_ExportedBookDetailInfo = new List<ExportBookDetailInfo>();
        private ExportBookManager exportBookManager;
        private ExportBookDetailManager exportBookDetailManager;
     
        public frmExportBooks()
        {
            InitializeComponent();
            this.exportBookDetailManager = new ExportBookDetailManager();
            this.exportBookManager = new ExportBookManager();
            this.txtDiscountPercent.Text = "0";
            this.txtTotalPrice.Text = "0";
            this.txtDiscount.Text = "0";
            this.txtTax.Text = "0";
        }

        private void LoadCustomer()
        {
            this.lueCustomer.Properties.DataSource = this.customerManager.ListCustomer();
            this.lueCustomer.Properties.DisplayMember = "Code";
            this.lueCustomer.Properties.ValueMember = "Id";
        }
        private void LoadBook()
        { 
            this.lueBookCode.Properties.DataSource = this.booksManager.ListBook();
            this.lueBookCode.Properties.DisplayMember = "Code";
            
        }
        private void LoadExportedBook()
        {
            this.gridExportedBooks.DataSource =L_ExportedBookDetailInfo;
        }

        private void frmExportedBooks_Load(object sender, EventArgs e)
        {
            this.LoadCustomer();
            this.LoadStore();
            this.LoadBook();

            this.dteExportedDate.DateTime = DateTime.Now;
         
        }
        private void LoadStore()
        {
            this.lueStore.Properties.DataSource = storeManager.ListStore();
            this.lueStore.Properties.DisplayMember = "Name";
            this.lueStore.Properties.ValueMember = "Id";
        }

        private void lueCustomer_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            ButtonEdit editor = (ButtonEdit)sender;
            EditorButton Button = e.Button;
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)
            {
                var form = new frmCustomerAdd();
                if(form.ShowDialog()==DialogResult.OK)
                {
                    this.LoadCustomer();
                }
            }
        }

        private void lueCustomer_EditValueChanged(object sender, EventArgs e)
        {
            this.txtCustomerName.Text = this.customerManager.GetCustomerByCode(this.lueCustomer.Text.Trim()).Name;
            this.txtCustomerContactor.Text = this.customerManager.GetCustomerByCode(this.lueCustomer.Text.Trim()).Contactor;
            this.txtCustomerContactorMobile.Text = this.customerManager.GetCustomerByCode(this.lueCustomer.Text.Trim()).ContactorMobile;
            this.txtOldLiabilities.Text = this.customerManager.GetCustomerByCode(this.lueCustomer.Text.Trim()).Liabilities.ToString();
            this.dxepCustomer.ClearErrors();
        }

        private void lueBookCode_EditValueChanged(object sender, EventArgs e)
        {
            this.dxepBookCode.ClearErrors();
            this.txtBookName.Text = this.booksManager.GetBookByCode(this.lueBookCode.Text.Trim()).Name;
            this.txtBookPrice.Text=this.booksManager.GetBookByCode(this.lueBookCode.Text.Trim()).Price.ToString();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (this.lueCustomer.Text.Trim() == string.Empty)
            {
                this.dxepCustomer.SetError(this.lueCustomer, "Lựa chọn khách hàng");
                this.lueCustomer.Focus();
                return;
            }
            if (this.lueBookCode.Text.Trim() == string.Empty)
            {
                this.dxepBookCode.SetError(this.lueBookCode, "Lựa chọn sách");
                this.lueBookCode.Focus();
                return;
            }
            else if (this.txtQuanlity.Text==string.Empty)
            {
                this.dxepQuanlity.SetError(this.txtQuanlity, "Kiểm tra số lượng");
                this.txtQuanlity.Focus();
                return;
            }

            try
            {

                var exportedBookDetailInfo = new ExportBookDetailInfo();
                exportedBookDetailInfo.Id = 1;
                exportedBookDetailInfo.BookCode = lueBookCode.Text.Trim();
                exportedBookDetailInfo.BookId = this.booksManager.GetBookByCode(this.lueBookCode.Text.Trim()).Id;
                exportedBookDetailInfo.BookName = this.txtBookName.Text.Trim();
                exportedBookDetailInfo.Price = float.Parse(this.txtBookPrice.Text.Trim());
                exportedBookDetailInfo.Quanlity = int.Parse(this.txtQuanlity.Text.Trim());
                exportedBookDetailInfo.DiscountPercent = int.Parse(this.txtDiscountPercent.Text.Trim());
                exportedBookDetailInfo.TotalPrice = exportedBookDetailInfo.Price * exportedBookDetailInfo.Quanlity / 100 * (100 - exportedBookDetailInfo.DiscountPercent);
                this.totalPrice(exportedBookDetailInfo.TotalPrice);
                L_ExportedBookDetailInfo.Add(exportedBookDetailInfo);
                this.LoadExportedBook();
                this.gridExportedBooks.RefreshDataSource();
            }
            catch (Exception)
            {
                
             XtraMessageBox.Show("Lỗi! Kiểm tra lại dữ liệu","Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void totalPrice(float price)
        {
            this.txtTotalPrice.Text = (float.Parse(this.txtTotalPrice.Text) + price).ToString();
            this.txtTotalAmount.Text=(float.Parse(this.txtTotalPrice.Text)/100*(100+float.Parse(this.txtTax.Text)-float.Parse(this.txtDiscount.Text))).ToString();
            this.txtPaymentRequest.Text = (float.Parse(this.txtTotalAmount.Text.Trim()) + float.Parse(this.txtOldLiabilities.Text.Trim())).ToString();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmExportBooks_FormClosed(object sender, FormClosedEventArgs e)
        {
            frmMain.MainWindowManager.WindowNames.Remove(this.Name);
            frmMain.MainWindowManager.Windows.Remove(this);
        }

        private void txtQuanlity_EditValueChanged(object sender, EventArgs e)
        {
            if (this.txtQuanlity.Text.Trim() != string.Empty)
            {
                this.dxepQuanlity.ClearErrors();
            }

        }

        private void txtCode_EditValueChanged(object sender, EventArgs e)
        {
            if (this.txtCode.Text.Trim() != String.Empty)
            {
                this.dxepCode.ClearErrors();
            }
            if (this.exportBookManager.HasCodeExisted(this.txtCode.Text.Trim()))
            {
                this.dxepCode.SetError(this.txtCode, "Mã phiếu nhập đã tồn tại");
                this.txtCode.Focus();
                return;
            }
            else
            {
                this.dxepCode.ClearErrors();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.lueCustomer.Text.Trim() == String.Empty)
            {
                this.dxepCustomer.SetError(this.lueCustomer, "Chọn nhà cung cấp");
                this.lueCustomer.Focus();
                return;
            }
            else if (this.txtCode.Text.Trim() == String.Empty)
            {
                this.dxepCode.SetError(this.txtCode, "Nhập mã hóa đơn");
                this.txtCode.Focus();
                return;
            }
            else if (this.exportBookManager.HasCodeExisted(this.txtCode.Text.Trim()))
            {
                this.dxepCode.SetError(this.txtCode, "Mã phiếu nhập đã tồn tại");
                this.txtCode.Focus();
                return;
            }
            else if (this.lueStore.Text.Trim() == String.Empty)
            {
                this.dxepStore.SetError(this.lueStore, "Lựa chọn cửa hàng");
                this.lueStore.Focus();
                return;
            }
            else if (this.txtPayment.Text.Trim() == String.Empty)
            {

                this.dxepPayment.SetError(this.txtPayment, "Nhập tiền thanh toán");
                this.txtPayment.Focus();
                return;
            }
            else
            {
                this.dxepCode.ClearErrors();
                this.dxepCustomer.ClearErrors();
                this.dxepStore.ClearErrors();
                this.dxepPayment.ClearErrors();
                this.dxepBookCode.ClearErrors();
            }

            try
            {
                //save exportBook
                var _exportBook = new ExportBook();
                _exportBook.Code = this.txtCode.Text.Trim();
                _exportBook.ExportDate = this.dteExportedDate.DateTime;
                _exportBook.Status = 1;
                _exportBook.Tax = int.Parse(this.txtTax.Text.Trim());
                _exportBook.TotalAmount = float.Parse(this.txtTotalAmount.Text.Trim());
                _exportBook.CustomerId = this.customerManager.GetCustomerByCode(this.lueCustomer.Text.Trim()).Id;
                _exportBook.CreatedBy = "Admin";
                _exportBook.CreatedDate = DateTime.Now;
                _exportBook.ModifiedBy = "Admin";
                _exportBook.ModifiedDate = DateTime.Now;
                this.exportBookManager.CreateExportBook(_exportBook);

                //save export detail
                foreach (ExportBookDetailInfo item in L_ExportedBookDetailInfo)
                {
                    var _exportBookDetail = new ExportBookDetail();
                    _exportBookDetail.ExportId = _exportBook.Id;
                    _exportBookDetail.BookId = item.BookId;
                    _exportBookDetail.Price = item.Price;
                    _exportBookDetail.Quantity = item.Quanlity;
                    _exportBookDetail.DiscountPercent = item.DiscountPercent;
                    _exportBookDetail.TotalPrice = item.TotalPrice;
                    _exportBookDetail.StoreId = this.storeManager.GetStoreByName(this.lueStore.Text.Trim()).Id;
                    this.exportBookDetailManager.CreateExportBookDetail(_exportBookDetail);


                    //update quality bookstore
                    var bookSore = this.bookStoreManager.GetBookStore(_exportBookDetail.BookId, _exportBookDetail.StoreId);
                    bookSore.Quantity -= _exportBookDetail.Quantity;
                    this.bookStoreManager.UpdateBookStore(bookSore);

                }

                var _customer = this.customerManager.GetCustomerByCode(this.lueCustomer.Text.Trim());
                _customer.Liabilities = float.Parse(this.txtNewLiabilities.Text.Trim());
                customerManager.UpdateCustomer(_customer);

                XtraMessageBox.Show("Thành công");
            }
            catch (Exception)
            {
                
               XtraMessageBox.Show("Lỗi! Kiểm tra lại dữ liệu","Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void txtTax_EditValueChanged(object sender, EventArgs e)
        {
            if (this.txtDiscount.Text != String.Empty)
            {
                this.txtTotalAmount.Text = (float.Parse(this.txtTotalPrice.Text) / 100 * (100 + float.Parse(this.txtTax.Text) - float.Parse(this.txtDiscount.Text))).ToString();
            }
        }
        private void txtDiscount_EditValueChanged(object sender, EventArgs e)
        {
            if (this.txtTax.Text != String.Empty)
            {
                this.txtTotalAmount.Text = (float.Parse(this.txtTotalPrice.Text) / 100 * (100 + float.Parse(this.txtTax.Text) - float.Parse(this.txtDiscount.Text))).ToString();
            }
        }

        private void txtPayment_EditValueChanged(object sender, EventArgs e)
        {
            if (this.txtPayment.Text != String.Empty)
            {
                this.txtNewLiabilities.Text = (float.Parse(this.txtPaymentRequest.Text.Trim()) - float.Parse(this.txtPayment.Text.Trim())).ToString();
                this.dxepPayment.ClearErrors();
            }

        }

        private void lueStore_EditValueChanged(object sender, EventArgs e)
        {
            this.dxepStore.ClearErrors();
        }

        private void txtTotalAmount_EditValueChanged(object sender, EventArgs e)
        {
            if (txtTotalAmount.Text.Trim() != String.Empty&&this.txtOldLiabilities.Text.Trim()!=String.Empty)
            {
                this.txtPaymentRequest.Text = (float.Parse(this.txtTotalAmount.Text.Trim()) + float.Parse(this.txtOldLiabilities.Text.Trim())).ToString();
            }
        }






    }
}